﻿using log4net;
using MeterSim.Socket;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;

namespace MeterSim {
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow: Window {

        private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));

        private readonly IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();

        private bool running = false;

        public MainWindow() {
            InitializeComponent();
            InitSocket(); // 初始化 Socket 服务端
        }

        // 初始化 Socket 服务端
        private void InitSocket() {
            if (port != null) {
                SocketServer.port = int.Parse(port.Text);
            }
            if (!bootstrap.Initialize()) {
                log.Error("SocketServer Initialize Failed");
            }
        }

        private void StartServer() {
            if (interval != null) {
                SocketServer.interval = int.Parse(interval.Text);
            }
            if (bootstrap.Start() == StartResult.Failed) {
                log.Error("SocketServer Start Failed");
                return;
            }
        }

        private void StopServer() {
            bootstrap.Stop();
        }

        private void InitOrderSource() {
            List<Order> list = new List<Order>();
            list.Add(new Order { ID = 1, Name = "正序" });
            list.Add(new Order { ID = 2, Name = "反序" });
            order.ItemsSource = list;
        }

        private void RenderTemplate() {
            if (msgLen == null || startFlag == null || dataIdx == null || dataLen == null || order == null || currentData == null) {
                return;
            }

            int intMsgLen = int.Parse(msgLen.Text); // 报文长度
            string strStartFlag = startFlag.Text; // 起始标识
            int intDataIdx = int.Parse(dataIdx.Text); // 读数索引
            int intDataLen = int.Parse(dataLen.Text); // 读数长度
            int intOrder = order.SelectedIndex; // 0 -> 正序, 1 -> 反序
            string strCurrentData = currentData.Text; // 当前读数

            string message = strStartFlag;
            for (int i = 1; i < intMsgLen - 2; i++) {
                if (i >= intDataIdx && i < intDataIdx + intDataLen) {
                    int idx = intOrder == 0 ? i - intDataIdx : intDataLen - 1 - i + intDataIdx;
                    if (idx < strCurrentData.Length) {
                        message += " 3" + strCurrentData.Substring(idx, 1);
                    } else {
                        message += " 00";
                    }
                } else {
                    message += " 00";
                }
            }

            Paragraph para = new Paragraph();
            para.Inlines.Add(new Run(message + " 0D 0A"));
            template.Document.Blocks.Clear();
            template.Document.Blocks.Add(para);

            SocketServer.message = message;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e) {
            InitOrderSource();
            RenderTemplate();
        }

        private void Window_Closed(object sender, System.EventArgs e) {
            StopServer(); // Stop the SocketServer
        }

        private void startBtn_Click(object sender, RoutedEventArgs e) {
            running = !running;
            if (running) {
                startBtn.Content = "停止";
                interval.IsEnabled = false;
                port.IsEnabled = false;
                StartServer();
            } else {
                startBtn.Content = "启动";
                interval.IsEnabled = true;
                port.IsEnabled = true;
                StopServer();
            }
        }

        private void TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) {
            RenderTemplate();
        }

        private void SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
            RenderTemplate();
        }

        private void dataSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
            int len = int.Parse(dataLen.Text);
            string value = (e.NewValue + Math.Pow(10, len + 1)).ToString();
            currentData.Text = value.Substring(value.Length - len, len);
            RenderTemplate();
        }

        private void dataMax_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) {
            if (dataSlider == null || dataMax == null) {
                return;
            }
            dataSlider.Maximum = int.Parse(dataMax.Text);
        }
    }

    public class Order {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}
